import json

from infirmary_admin_src.infirmary_common.infirmary_controller import IBaseController
from infirmary_admin_src.infirmary_common.infirmary_controller.rest_controller_with_depends import \
    RestControllerWithDepends
from fastapi import Request, Depends, Path

from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.infirmary.businesses.schemas import SchemaBase
from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.system.login.services import LogicBusinesses
from infirmary_admin_src.infirmary_smart_admin.infirmary_utils.convert2_help import convert_dict_to_camel_case



class XParam(SchemaBase):
    '''
    账号密码登录参数
    '''
    onlyMenu: bool = True


class IController(IBaseController):
    '''
    定制相关约束检测函数逻辑步序
    '''

    def __init__(self, *, request: Request,
                 schema_param: XParam = Depends(),
                 ):
        super().__init__(request=request)
        # 入参参数
        # 入参参数
        self.schema_param = schema_param


def cached(func):
    '''缓存装饰器'''
    cache = {}

    def wrapper(data, parent_id=None):
        # 如果缓存中存在相应的结果，则直接返回
        if parent_id in cache:
            return cache[parent_id]
        # 否则调用函数计算结果并更新缓存
        result = func(data, parent_id)
        cache[parent_id] = result
        return result

    return wrapper


def generate_tree(data, parent_id=0):
    # 根据父id递归生成树状结构
    children = []
    for item in data:
        if item['parentId'] == parent_id:
            subchildren = generate_tree(tuple(data), item['menuId'])
            if subchildren:
                item['children'] = subchildren
            children.append(item)
    return children


@RestControllerWithDepends()
class SystemMenuTreeController(IController):

    def business_login(self):
        pass
        menuList = LogicBusinesses.get_sys_employee_menuList_only_menu()
        result = [{**{'apiPermsList': None}, **convert_dict_to_camel_case(v, passkey=['contextMenuId',
                                                                                      'createUserId',
                                                                                      'menuType',
                                                                                      'parentId',
                                                                                      ],
                                                                          keepkey=['permsType', 'updateUserId',
                                                                                   'menuId', 'sort'],
                                                                          ),
                   } for v in menuList]
        return generate_tree(result, 0)
